package cn.cocho.custom.yunCashierDf.pay.controller;
import cn.cocho.common.web.app.JsonResultContants;
import cn.cocho.custom.yunCashierDf.common.controller.EncryptCode;
import cn.cocho.custom.yunCashierDf.common.controller.HttpSubmit;
import cn.cocho.custom.yunCashierDf.common.controller.QRCodeUtil;
import cn.cocho.custom.yunCashierDf.merchant.domain.AsyncRequestInfo;
import cn.cocho.custom.yunCashierDf.merchant.domain.MerchantInfo;
import cn.cocho.custom.yunCashierDf.merchant.domain.MerchantTransactionInfo;
import cn.cocho.custom.yunCashierDf.merchant.service.AsyncRequestInfoService;
import cn.cocho.custom.yunCashierDf.merchant.service.MerchantInfoService;
import cn.cocho.custom.yunCashierDf.merchant.service.MerchantTransactionInfoService;
import cn.cocho.custom.yunCashierDf.utils.JsonResult;
import cn.cocho.custom.yunCashierDf.utils.StringUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by WQJ on 2017-05-26.
 */
@Controller
public class PayController {

    @Autowired
    private MerchantInfoService merchantInfoService;

    @Autowired
    private AsyncRequestInfoService asyncRequestInfoService;

    @Autowired
    private MerchantTransactionInfoService merchantTransactionInfoService;

    //预下单接口
    @ResponseBody
    @RequestMapping(value = "/anonymous/pay/toPuat")
    public JsonResult toPuat(String merchantId,String chcdPara ,String origOrderNumPara,String terminalidPara,String txamtPara,HttpServletRequest request) throws IOException {
        MerchantInfo merchantInfo = merchantInfoService.getMerchantInfoById(merchantId);
        JsonResult result = null;
        if(merchantInfo != null){
            String backUrl = merchantInfo.getBackUrl();
            //支付类型
            String busicd = "PAUT";
            //编码格式
            String charset = merchantInfo.getCharset();
            //支付类型
            String chcd = chcdPara;
            //机构号
            String inscd = merchantInfo.getInscd();
            //商户号
            String mchntid = merchantInfo.getMchntid();
            //订单号
            String origOrderNum = origOrderNumPara;  //订单号
            //签名方式
            String signType = merchantInfo.getSignType();
            //终端号
            String terminalid = terminalidPara;
            //交易金额
            String txamt = txamtPara;  //钱数
            //交易方向
            String txndir = merchantInfo.getTxndir();
            //版本号
            String version = merchantInfo.getVersion();

            String newString = "backUrl="+backUrl+"&busicd="+busicd+"&charset="+charset+"&chcd="+chcd+"&inscd="+inscd+"&mchntid="+mchntid+"&orderNum="+origOrderNum+""
                               + "&signType="+signType+"&terminalid="+terminalid+"&txamt="+txamt+"&txndir="+txndir+"&version="+version+"";
            String newSign = newString + merchantInfo.getSignKey();
            System.out.println(newSign);
            String sign = new EncryptCode().SHA256(newSign);

            JSONObject jsonObj = new JSONObject();
            jsonObj.put("txndir", txndir);
            jsonObj.put("busicd", busicd);
            jsonObj.put("chcd", chcd);
            jsonObj.put("inscd", inscd);
            jsonObj.put("charset", charset);
            jsonObj.put("mchntid", mchntid);
            jsonObj.put("signType", signType);
            jsonObj.put("terminalid", terminalid);
            jsonObj.put("txamt", txamt);
            jsonObj.put("orderNum", origOrderNum);
            jsonObj.put("backUrl", backUrl);
            jsonObj.put("version", version);
            jsonObj.put("sign",sign );

            String jsonString = jsonObj.toString();
            System.out.println(jsonString);
            //获取返回值
            String returnValue = new HttpSubmit().postAttendanceInfo(jsonString, StringUtil.requestUrl);
            //解析json数据
            JSONObject jsonObject = JSONObject.fromObject(returnValue);
            String qrcode = null;
            String localUrl = null;
            if(jsonObject.getString("respcd").equals("09")){
                qrcode = jsonObject.getString("qrcode");
                //生成二维码
                String local = request.getRealPath("/") + "/images";
                System.out.println(local);
                try {
                    localUrl = QRCodeUtil.encode(qrcode, local,origOrderNum, true);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                MerchantTransactionInfo merchantTransactionInfo = new MerchantTransactionInfo();
                merchantTransactionInfo.setPaymentType(busicd);
                merchantTransactionInfo.setMerchantId(merchantInfo.getMerchantId());
                merchantTransactionInfo.setBusicd(busicd);
                int temp=(int)(Math.random()*100000);
                while(temp/10000<1){
                    temp=(int)(Math.random()*100000);
                }
                merchantTransactionInfo.setOrderNum(new SimpleDateFormat("yyyyMMddHHmmssSSS") .format(new Date())+temp);
                merchantTransactionInfo.setOrigOrderNum(origOrderNum);
                merchantTransactionInfo.setChcd(chcd);
                merchantTransactionInfo.setRespcd(jsonObject.getString("respcd"));
                merchantTransactionInfo.setTxamt(txamt);
                merchantTransactionInfo.setSign(sign);
                merchantTransactionInfo.setQrcode(qrcode);
                merchantTransactionInfo.setTerminalid(terminalid);
                merchantTransactionInfo.setSearchStatus("0");
                merchantTransactionInfoService.insertMerchantTransactionInfo(merchantTransactionInfo);

                String QRcodeUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/yunCashierDf/images/" + localUrl;
                jsonObject.put("QRcodeUrl",QRcodeUrl);
            }
            result = new JsonResult(JsonResultContants.SUCCESS, "请求预下单接口成功", jsonObject);
        }else{
            JSONObject returnJson = new JSONObject();
            returnJson.put("errorDetail","请求预下单接口出错");
            result = new JsonResult(JsonResultContants.FAIL, "请求预下单接口失败", returnJson);
        }
        return result;
    }

    //查询接口
    @ResponseBody
    @RequestMapping(value = "/anonymous/pay/toInqy")
    public JsonResult toInqy(String merchantId,String origOrderNumPara,String terminalidPara) throws IOException {
        MerchantInfo merchantInfo = merchantInfoService.getMerchantInfoById(merchantId);
        JsonResult result = null;
        if(merchantInfo != null){
            //查询接口
            String busicd = "INQY";
            String charset = merchantInfo.getCharset();
            String inscd = merchantInfo.getInscd();
            String mchntid = merchantInfo.getMchntid();
            String origOrderNum = origOrderNumPara;  //使用进行过预下单的订单号进行查询
            String signType = merchantInfo.getSignType();
            String terminalid = terminalidPara;
            String txndir = merchantInfo.getTxndir();
            String version = merchantInfo.getVersion();

            String newString = "busicd="+busicd+"&charset="+charset+"&inscd="+inscd+"&mchntid="+mchntid+"&origOrderNum="+origOrderNum+""
                               + "&signType="+signType+"&terminalid="+terminalid+"&txndir="+txndir+"&version="+version+"";

            String newSign = newString + merchantInfo.getSignKey();
            String sign = new EncryptCode().SHA256(newSign);

            JSONObject jsonObj = new JSONObject();
            jsonObj.put("txndir", txndir);
            jsonObj.put("busicd", busicd);
            jsonObj.put("inscd", inscd);
            jsonObj.put("charset", charset);
            jsonObj.put("mchntid", mchntid);
            jsonObj.put("signType", signType);
            jsonObj.put("terminalid", terminalid);
            jsonObj.put("origOrderNum", origOrderNum);
            jsonObj.put("version", version);
            jsonObj.put("sign", sign);

            String jsonString = jsonObj.toString();

            //获取返回值
            String returnValue = new HttpSubmit().postAttendanceInfo(jsonString, StringUtil.requestUrl);
            System.out.println("返回结果"+returnValue);
            JSONObject jsonObject = JSONObject.fromObject(returnValue);

            MerchantTransactionInfo merchantTransactionInfo = merchantTransactionInfoService.getMerchantTransactionInfo(merchantInfo.getMerchantId(),origOrderNum);
            merchantTransactionInfo.setRespcd(jsonObject.getString("respcd"));
            merchantTransactionInfo.setBusicd(jsonObject.getString("busicd"));
            merchantTransactionInfo.setSearchStatus("1");
            if(merchantTransactionInfo.getRespcd().equals("00")){
               merchantTransactionInfo.setChannelOrderNum(jsonObject.getString("channelOrderNum"));
            }
            merchantTransactionInfoService.replaceMerchantTransactionInfo(merchantTransactionInfo);
            result = new JsonResult(JsonResultContants.SUCCESS, "请求查询接口成功", jsonObject);
        }else{
            JSONObject returnJson = new JSONObject();
            returnJson.put("errorDetail", "请求接口出错");
            result = new JsonResult(JsonResultContants.FAIL, "请求查询接口失败", returnJson);
        }
        return result;
    }

    //取消订单
    @ResponseBody
    @RequestMapping(value = "/anonymous/pay/toCanc")
    public JsonResult toCanc(String merchantId,String origOrderNumPara,String terminalidPara) throws IOException {
        MerchantInfo merchantInfo = merchantInfoService.getMerchantInfoById(merchantId);
        MerchantTransactionInfo merchantTransactionInfo = merchantTransactionInfoService.getMerchantTransactionInfo(merchantInfo.getMerchantId(),origOrderNumPara);
        JsonResult result = null;
        if(merchantInfo != null && merchantTransactionInfo != null){
            String busicd = "CANC";
            String charset = merchantInfo.getCharset();
            String inscd = merchantInfo.getInscd();
            String mchntid = merchantInfo.getMchntid();
            String orderNum = merchantTransactionInfo.getOrderNum();
            String origOrderNum = origOrderNumPara;  //使用进行过预下单的订单号进行查询
            String signType = merchantInfo.getSignType();
            String terminalid = terminalidPara;
            String txndir = merchantInfo.getTxndir();
            String version = merchantInfo.getVersion();

            String newString = "busicd="+busicd+"&charset="+charset+"&inscd="+inscd+"&mchntid="+mchntid+"&orderNum="+orderNum+"&origOrderNum="+origOrderNum+""
                               + "&signType="+signType+"&terminalid="+terminalid+"&txndir="+txndir+"&version="+version+"";

            String newSign = newString + merchantInfo.getSignKey();
            String sign = new EncryptCode().SHA256(newSign);

            JSONObject jsonObj = new JSONObject();
            jsonObj.put("txndir", txndir);
            jsonObj.put("busicd", busicd);
            jsonObj.put("inscd", inscd);
            jsonObj.put("charset", charset);
            jsonObj.put("mchntid", mchntid);
            jsonObj.put("signType", signType);
            jsonObj.put("terminalid", terminalid);
            jsonObj.put("orderNum", orderNum);
            jsonObj.put("origOrderNum", origOrderNum);
            jsonObj.put("version", version);
            jsonObj.put("sign", sign);

            String jsonString = jsonObj.toString();

            //获取返回值
            String returnValue = new HttpSubmit().postAttendanceInfo(jsonString, StringUtil.requestUrl);
            System.out.println("返回结果"+returnValue);
            //解析json数据
            JSONObject jsonObject = JSONObject.fromObject(returnValue);
            merchantTransactionInfo.setRespcd(jsonObject.getString("respcd"));
            merchantTransactionInfo.setBusicd(jsonObject.getString("busicd"));
            if(merchantTransactionInfo.getRespcd().equals("Y9")){
               merchantTransactionInfoService.replaceMerchantTransactionInfo(merchantTransactionInfo);
            }else{
                merchantTransactionInfo.setRespcd("Y9");
                merchantTransactionInfoService.replaceMerchantTransactionInfo(merchantTransactionInfo);
            }
            result = new JsonResult(JsonResultContants.SUCCESS, "请求取消接口成功", jsonObject);
        }else{
            JSONObject returnJson = new JSONObject();
            returnJson.put("errorDetail", "请求取消接口出错");
            result = new JsonResult(JsonResultContants.FAIL, "请求取消接口失败", returnJson);
        }
        return result;
    }

    //退款订单
    @ResponseBody
    @RequestMapping(value = "/anonymous/pay/toRefd")
    public JsonResult toRefd(String merchantId,String origOrderNumPara,String terminalidPara) throws IOException {
        MerchantInfo merchantInfo = merchantInfoService.getMerchantInfoById(merchantId);
        MerchantTransactionInfo merchantTransactionInfo = merchantTransactionInfoService.getMerchantTransactionInfo(merchantInfo.getMerchantId(),origOrderNumPara);
        JsonResult result = null;
        if(merchantInfo != null && merchantTransactionInfo != null){
            String busicd = "REFD";
            String charset = merchantInfo.getCharset();
            String inscd = merchantInfo.getInscd();
            String mchntid = merchantInfo.getMchntid();
            String orderNum = merchantTransactionInfo.getOrderNum();
            String origOrderNum = origOrderNumPara;  //使用进行过预下单的订单号进行查询
            String signType = merchantInfo.getSignType();
            String terminalid = terminalidPara;
            String txamt = merchantTransactionInfo.getTxamt();  //钱数
            String txndir = merchantInfo.getTxndir();
            String version = merchantInfo.getVersion();

            String newString = "busicd="+busicd+"&charset="+charset+"&inscd="+inscd+"&mchntid="+mchntid+"&orderNum="+orderNum+"&origOrderNum="+origOrderNum+""
                               + "&signType="+signType+"&terminalid="+terminalid+"&txamt="+txamt+"&txndir="+txndir+"&version="+version+"";

            String newSign = newString + merchantInfo.getSignKey();
            String sign = new EncryptCode().SHA256(newSign);

            JSONObject jsonObj = new JSONObject();
            jsonObj.put("txndir", txndir);
            jsonObj.put("busicd", busicd);
            jsonObj.put("inscd", inscd);
            jsonObj.put("charset", charset);
            jsonObj.put("mchntid", mchntid);
            jsonObj.put("signType", signType);
            jsonObj.put("terminalid", terminalid);
            jsonObj.put("orderNum", orderNum);
            jsonObj.put("origOrderNum", origOrderNum);
            jsonObj.put("version", version);
            jsonObj.put("txamt", txamt);
            jsonObj.put("sign", sign);

            String jsonString = jsonObj.toString();
            System.out.println(jsonString);

            //获取返回值
            String returnValue = new HttpSubmit().postAttendanceInfo(jsonString, StringUtil.requestUrl);
            JSONObject jsonObject = JSONObject.fromObject(returnValue);
            merchantTransactionInfo.setRespcd(jsonObject.getString("respcd"));
            merchantTransactionInfo.setBusicd(jsonObject.getString("busicd"));
            merchantTransactionInfoService.replaceMerchantTransactionInfo(merchantTransactionInfo);
            result = new JsonResult(JsonResultContants.SUCCESS, "请求退款接口成功", jsonObject);
        }else{
            JSONObject returnJson = new JSONObject();
            returnJson.put("errorDetail", "请求退款接口出错");
            result = new JsonResult(JsonResultContants.FAIL, "请求退款接口失败", returnJson);
        }
        return result;
    }

    //异步通知接口
    @ResponseBody
    @RequestMapping(value = "/anonymous/pay/callBackUrl")
    public String callBackUrl(HttpServletRequest request) throws IOException {
        System.out.println("进入异步请求！");
        //根据订单号和终端号取出商户ID信息
        String result = "ERROR";
        String origOrderNumRequest = request.getParameter("orderNum");
        System.out.println(origOrderNumRequest);
        if(origOrderNumRequest != null){
            /*AsyncRequestInfo asyncRequestInfo = new AsyncRequestInfo();

            asyncRequestInfo.setVersion(request.getParameter("version"));
            asyncRequestInfo.setSignType(request.getParameter("signType"));
            asyncRequestInfo.setCharset(request.getParameter("charset"));
            asyncRequestInfo.setOrderNum(request.getParameter("orderNum"));
            asyncRequestInfo.setBusicd(request.getParameter("busicd"));
            asyncRequestInfo.setRespcd(request.getParameter("respcd"));
            asyncRequestInfo.setInscd(request.getParameter("inscd"));
            asyncRequestInfo.setChcd(request.getParameter("chcd"));
            asyncRequestInfo.setMchntid(request.getParameter("mchntid"));
            asyncRequestInfo.setTerminalid(request.getParameter("terminalid"));*/
            /*asyncRequestInfo.setTxamt(request.getParameter("txamt"));
            asyncRequestInfo.setTxndir(request.getParameter("txndir"));
            asyncRequestInfo.setChannelOrderNum(request.getParameter("channelOrderNum"));
            asyncRequestInfo.setErrorDetail(request.getParameter("errorDetail"));
            asyncRequestInfo.setSign(request.getParameter("sign"));
            asyncRequestInfo.setBankType(request.getParameter("bankType"));*/
            //asyncRequestInfo.setTransTime(request.getParameter("transTime"));
            //asyncRequestInfo.setConsumerAccount(request.getParameter("consumerAccount"));
            //asyncRequestInfoService.add(asyncRequestInfo);

            String terminalidRequest = request.getParameter("terminalid");
            String respcdRequest = request.getParameter("respcd");
            System.out.println(origOrderNumRequest+"!!!"+terminalidRequest+"!!!"+respcdRequest);
            MerchantTransactionInfo merchantTransactionInfo = merchantTransactionInfoService.getMerchantTransactionInfoCall(origOrderNumRequest,terminalidRequest);
            if(merchantTransactionInfo.getSearchStatus().equals("0")){
                //根据商户ID取出商户信息
                MerchantInfo merchantInfo = merchantInfoService.getMerchantInfoById(merchantTransactionInfo.getMerchantId());
                if(merchantInfo != null){
                    System.out.println("开始组装参数");
                    String busicd = "INQY";
                    String charset = merchantInfo.getCharset();
                    String inscd = merchantInfo.getInscd();
                    String mchntid = merchantInfo.getMchntid();
                    String origOrderNum = origOrderNumRequest;  //使用进行过预下单的订单号进行查询
                    String signType = merchantInfo.getSignType();
                    String terminalid = terminalidRequest;
                    String txndir = merchantInfo.getTxndir();
                    String version = merchantInfo.getVersion();
                    String newString = "busicd="+busicd+"&charset="+charset+"&inscd="+inscd+""+ "&mchntid="+mchntid+"&origOrderNum="+origOrderNum+""
                            + "&signType="+signType+"&terminalid="+terminalid+""+ "&txndir="+txndir+"&version="+version+"";

                    String newSign = newString + merchantInfo.getSignKey();
                    String sign = new EncryptCode().SHA256(newSign);

                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("txndir", txndir);
                    jsonObj.put("busicd", busicd);
                    jsonObj.put("inscd", inscd);
                    jsonObj.put("charset", charset);
                    jsonObj.put("mchntid", mchntid);
                    jsonObj.put("signType", signType);
                    jsonObj.put("terminalid", terminalid);
                    jsonObj.put("origOrderNum", origOrderNum);
                    jsonObj.put("version", version);
                    jsonObj.put("sign", sign);

                    String jsonString = jsonObj.toString();

                    //获取返回值　//计算请求时间
                    System.out.println("开始发出查询请求！");
                    String returnValue = new HttpSubmit().postAttendanceInfo(jsonString, StringUtil.requestUrl);

                    System.out.println("返回结果"+returnValue);
                    JSONObject jsonObject = JSONObject.fromObject(returnValue);
                    merchantTransactionInfo.setRespcd(jsonObject.getString("respcd"));
                    merchantTransactionInfo.setBusicd(jsonObject.getString("busicd"));
                    merchantTransactionInfo.setSearchStatus("1");
                    if(respcdRequest.equals(merchantTransactionInfo.getRespcd())){
                        merchantTransactionInfo.setChannelOrderNum(jsonObject.getString("channelOrderNum"));
                        merchantTransactionInfoService.replaceMerchantTransactionInfo(merchantTransactionInfo);
                        result = "SUCCESS";
                        if(merchantInfo.getIsPay().equals("1")){

                            /*int temp=(int)(Math.random()*100000);
                            while(temp/10000<1){
                                temp=(int)(Math.random()*100000);
                            }*/
                            //merchantTransactionInfo.setOrderNum(new SimpleDateFormat("yyyyMMddHHmmssSSS") .format(new Date())+temp);

                            System.out.println("开始组装代付参数");
                            String busicdDf = "193000";
                            String txndirDf = "Q";
                            String posentrymode = "012";
                            String txcurrcdDf = "156";
                            String chcdDf = "92401888";
                            String clisnDf = merchantInfo.getMchntid() + merchantTransactionInfo.getTerminalid() + new SimpleDateFormat("yyyyMMdd");
                            String localdtDf = String.valueOf(new Date().getTime());
                            String usagetagsDf = "01";
                            //申请代付
                            JSONObject jsonObjDf = new JSONObject();
                            jsonObjDf.put("busicd", busicdDf);
                            jsonObjDf.put("txndir", txndirDf);
                            jsonObjDf.put("posentrymode",posentrymode);
                            jsonObjDf.put("chcd",chcdDf);
                            jsonObjDf.put("clisn",clisnDf);
                            jsonObjDf.put("mchntid",merchantInfo.getMchntid());
                            jsonObjDf.put("terminalid",merchantTransactionInfo.getTerminalid());
                            jsonObjDf.put("txamt",merchantTransactionInfo.getTxamt());
                            jsonObjDf.put("txcurrcd",txcurrcdDf);
                            jsonObjDf.put("localdt",localdtDf);
                            jsonObjDf.put("usagetags",usagetagsDf);
                            jsonObjDf.put("acctno",merchantInfo.getAcctNo());
                            jsonObjDf.put("accttype",merchantInfo.getAcctType());
                            jsonObjDf.put("chname",merchantInfo.getChName());
                            jsonObjDf.put("chbank",merchantInfo.getChBank());
                            jsonObjDf.put("bankno",merchantInfo.getBankNo());
                            System.out.println("JSON字符串"+jsonObjDf.toString());
                            //发送请求
                            returnValue = new HttpSubmit().postAttendanceInfo(jsonObjDf.toString(), StringUtil.requestUrl);
                            System.out.println(returnValue + "返回的参数");
                        }

                    }else{
                        for(int i = 1;i <= 3; i++){
                            System.out.println("我是第"+i+"次请求！");
                            returnValue = new HttpSubmit().postAttendanceInfo(jsonString, StringUtil.requestUrl);
                            jsonObject = JSONObject.fromObject(returnValue);
                            merchantTransactionInfo.setRespcd(jsonObject.getString("respcd"));
                            merchantTransactionInfo.setBusicd(jsonObject.getString("busicd"));
                            merchantTransactionInfo.setSearchStatus("1");
                            if(respcdRequest.equals(merchantTransactionInfo.getRespcd())){
                                merchantTransactionInfo.setChannelOrderNum(jsonObject.getString("channelOrderNum"));
                                merchantTransactionInfoService.replaceMerchantTransactionInfo(merchantTransactionInfo);
                                result = "SUCCESS";
                                break;
                            }else{
                                if(i == 3){
                                    //取消订单
                                    new PayController().toCanc(merchantTransactionInfo.getMerchantId(),origOrderNumRequest,terminalidRequest);
                                    result = "请求超时，取消订单！";
                                }
                            }
                        }
                    }
                }else{
                    result = "请求异步通知接口出错！";
                }
                System.out.println("异步请求结果："+result);
            }else{
                result = "SUCCESS";
            }
        }else{
            result = "异步请求传递的参数错误！";
        }
        return result;
    }

}
